Skip to content

FlatDb: set long-finality reorg backstop to EIP-8252 retention window - #16457

Open
nerolation wants to merge 8 commits into
NethermindEth:masterfrom
nerolation:eip8252-reorg-retention
Open

nerolation wants to merge 8 commits into
NethermindEth:masterfrom
nerolation:eip8252-reorg-retention

Conversation

@nerolation

Copy link
Copy Markdown
Contributor

Raise the default FlatDb.LongFinalityMaxReorgDepth from 90000 to 262144, the EIP-8252 REORG_RETENTION_WINDOW (8192 epochs x 32 slots = 2^18 blocks, ~36.4 days). This is the force-persist backstop used under the default EnableLongFinality path: the persisted-snapshot tier serves reorgs down to this depth, so it is the deepest block whose post-state the node can reconstruct without sync while finality stalls. 90000 blocks (~12.5 days) fell short of the inactivity-leak-bounded non-finality span the EIP requires state to be retained across.

Introduce a named, documented FlatDbConfig.ReorgRetentionWindow constant for the default instead of a bare literal, and reference EIP-8252 in the config description. The non-long-finality MaxReorgDepth (256) and MinReorgDepth are left unchanged: EnableLongFinality=false remains the lower-resource opt-out. The value stays operator-overridable via --FlatDb.LongFinalityMaxReorgDepth.

Update the default-value regression test to assert the new default equals both the constant and 8192*32.

Changes

Remarks

Raise the default FlatDb.LongFinalityMaxReorgDepth from 90000 to 262144,
the EIP-8252 REORG_RETENTION_WINDOW (8192 epochs x 32 slots = 2^18 blocks,
~36.4 days). This is the force-persist backstop used under the default
EnableLongFinality path: the persisted-snapshot tier serves reorgs down to
this depth, so it is the deepest block whose post-state the node can
reconstruct without sync while finality stalls. 90000 blocks (~12.5 days)
fell short of the inactivity-leak-bounded non-finality span the EIP requires
state to be retained across.

Introduce a named, documented FlatDbConfig.ReorgRetentionWindow constant for
the default instead of a bare literal, and reference EIP-8252 in the config
description. The non-long-finality MaxReorgDepth (256) and MinReorgDepth are
left unchanged: EnableLongFinality=false remains the lower-resource opt-out.
The value stays operator-overridable via --FlatDb.LongFinalityMaxReorgDepth.

Update the default-value regression test to assert the new default equals both
the constant and 8192*32.
The long-finality backstop (LongFinalityMaxReorgDepth = REORG_RETENTION_WINDOW)
is correct, but the FlatDbConfig doc comment and the IFlatDbConfig description
overclaimed it: they read as "retain any canonical block within head-W under all
conditions". Nethermind does not do that under healthy finality -- state folds
toward the finalized boundary (PersistenceManager Phase 1), which EIP-8252 allows.
The window only bounds how deep the retained span may grow during a finality
stall. Reword both to the finality-aware framing; keep the EIP reference, the
8192x32 derivation, and the value.

Note in the config description that this window is honoured only by the flat-state
store; nodes on the legacy patricia-trie pruning store keep the fixed 64-block
Pruning.PruningBoundary.

Document the force-persist backstop's ~CompactSize slack: the strict `>` fires one
block past the window and a forced persist advances the base by up to CompactSize,
so retained depth dips to ~window - CompactSize -- within EIP tolerance, since the
window is the inactivity-leak upper bound, not an exact target.

Add a focused unit test asserting the force-persist backstop depth is the
REORG_RETENTION_WINDOW: at the default long-finality config a depth equal to the
window does not force-persist, one block past it does.
// longest chain, then the latest state, only when nothing was committed this session.
// The strict `>` fires one block past the backstop and FindSnapshotToPersist advances the base by
// up to CompactSize, so the retained reconstructable depth dips to ~_backstopReorgDepth - CompactSize
// right after a forced persist. That ~CompactSize (default 32) slack is within EIP-8252 tolerance:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] The new default can discard the last finalized post-state inside the advertised window. With history disabled, an aligned base B, finality stalled at B+16, and head B+262,145, the finalized gate skips B+32 and the forced gate opens. FindSnapshotToPersist can select the canonical compacted B→B+32 chunk, and AddToPersistence advances the base and prunes B+16. A competing branch whose first block builds on B+16 then lacks the state required by NewPayloadHandler, even though its common ancestor is only 262,129 blocks deep. EIP-8252 specifies an inclusive floor at head minus 262,144. Defer candidates ending above that floor or select a shorter candidate, and assert that the boundary state remains readable after persistence. The added test checks selection before pruning. Pinned EIP-8252 Specification

@kevaundray

Copy link
Copy Markdown
Contributor

Under stalled finality, the default config keeps 262,113 blocks of reconstructable state, not 262,144

Issue

EIP-8252 requires the post-state of every canonical block in [head - W, head] to be reconstructable, with no tolerance. With the defaults from this PR (LongFinalityMaxReorgDepth = 262144, CompactSize = 32):

  1. PersistenceManager.cs:180 fires the forced persist when snapshotsDepth > _backstopReorgDepth, i.e. at head H = P + W + 1.
  2. FindSnapshotToPersist (SnapshotRepository.cs:1137-1149, FindPersistPolicy) tries the CompactSized / InMemoryCompacted edges first, so the base moves forward by up to CompactSize, to P + 32.
  3. PersistenceManager.cs:344-348 sets CurrentPersistedStateId = toPersist.To and calls RemoveStatesUntil(...). Nothing can rebuild the state below the new base (HistoryEnabled is false by default, so there are no reverse diffs).

The window starts at H - W = P + 1, so blocks P+1 … P+31 are no longer reconstructable. This repeats every 32 blocks for as long as finality stays stalled. The comment added at PersistenceManager.cs:176-179 calls this "within EIP-8252 tolerance", but the EIP has no tolerance clause. It also contradicts the claim in LongFinalityIntegrationTests.cs that a default node "retains reconstructable state across the whole non-finality span".

Reproduce

Add this test to PersistenceManagerTests (it uses the existing fixture fields and helpers) on this branch (ab3bbed) and run:

dotnet test --project src/Nethermind/Nethermind.State.Flat.Test -c Release --filter "Name~Eip8252_ForcedPersist" --output Detailed
[Test]
public async Task Eip8252_ForcedPersist_KeepsWholeWindowReconstructable()
{
    FlatDbConfig config = new(); // production defaults: LongFinalityMaxReorgDepth = 262144, CompactSize = 32
    using PersistenceManager pm = new(
        config,
        ScheduleHelper.CreateWithOffset(config, 0),
        _finalizedStateProvider,
        _persistence,
        _snapshotRepository,
        NullStatePersistenceBarrier.Instance,
        LimboLogs.Instance,
        _persistedSnapshotCompactor,
        _tier.Loader,
        Substitute.For<IProcessExitSource>());
    ulong window = FlatDbConfig.ReorgRetentionWindow;

    // Canonical blocks 1..CompactSize, a compacted snapshot over them, then a compacted snapshot up to head = W + 1.
    List<Snapshot> leases = [];
    List<StateId> canonical = [Block0];
    for (ulong b = 1; b <= config.CompactSize; b++)
    {
        StateId s = CreateStateId(b);
        leases.Add(CreateSnapshot(canonical[^1], s));
        canonical.Add(s);
    }
    leases.Add(CreateSnapshot(Block0, canonical[^1], compacted: true));
    StateId head = CreateStateId(window + 1);
    leases.Add(CreateSnapshot(canonical[^1], head, compacted: true));
    _snapshotRepository.SetLastCommittedStateId(head);
    _finalizedStateProvider.SetFinalizedBlockNumber(0); // finality stalled

    await pm.AddToPersistence(head);

    ulong windowLow = head.BlockNumber - window;
    StateId persisted = pm.GetCurrentPersistedStateId();
    List<ulong> lost = [];
    for (ulong b = windowLow; b < persisted.BlockNumber; b++)
        if (!_snapshotRepository.HasState(canonical[(int)b])) lost.Add(b);
    TestContext.Out.WriteLine($"head={head.BlockNumber} window={window} windowLow={windowLow} persistedBase={persisted.BlockNumber} retainedDepth={head.BlockNumber - persisted.BlockNumber} lostInWindow={lost.Count} [{string.Join(",", lost)}]");
    foreach (Snapshot s in leases) s.Dispose();

    Assert.That(persisted.BlockNumber, Is.LessThanOrEqualTo(windowLow),
        "post-state of canonical blocks in [head-W, persistedBase) is no longer reconstructable");
}

Evidence (output at ab3bbed)

failed Eip8252_ForcedPersist_KeepsWholeWindowReconstructable
    post-state of canonical blocks in [head-W, persistedBase) is no longer reconstructable
    Expected: less than or equal to 1
    But was:  32
  Standard output
    head=262145 window=262144 windowLow=1 persistedBase=32 retainedDepth=262113 lostInWindow=31 [1,2,3,...,31]

The new DetermineSnapshotAction_BackstopAtRetentionWindow_* tests still pass because they only check whether a persist fires at W + 1, not how far the base moves when it does.

Suggested fix

Keep CompactSize of headroom: fire the forced persist at snapshotsDepth > W + CompactSize (or default the backstop to ReorgRetentionWindow + CompactSize), and add an assertion like the one above on what stays reconstructable after the persist.

…r a finality stall

The long-finality force-persist backstop (default LongFinalityMaxReorgDepth =
REORG_RETENTION_WINDOW) could prune a still-reconstructable post-state from inside
the advertised window. Under stalled finality the forced persist takes the widest
candidate extending the persisted base (a CompactSize chunk or a converted
compacted snapshot) and advances the base to its To, pruning every state below it
in both the in-memory and persisted-snapshot tiers. When that To sits above the
window floor head - W, a narrower per-block state between the floor and the new
base -- e.g. the finalized-but-unfinalized-depth block beneath a canonical
CompactSize chunk -- is stranded, so a competing branch building on it lacks the
required state even though the common ancestor is less than W deep.

Guard the forced persist: defer a candidate whose new base would prune a state
still reconstructable inside [head - W, head]. That is exactly when a wider
candidate skips a narrower in-window state, checked across both tiers since a deep
stall converts near-base states into the persisted-snapshot tier. A wider
candidate that skips no in-window state -- e.g. a single bulk-imported base --
still persists immediately. Conversion to the persisted tier keeps memory bounded
while a persist is deferred, and the floor rises one block per head, so the persist
fires once the floor reaches the candidate boundary and the new base lands exactly
on the floor -- no CompactSize gap, no in-window state pruned. The finalized
trigger needs no guard: it folds only up to the finalized block, which is never a
reorg target.

Reword the config summaries and CLI help: describe the setting as the
finality-stall backstop that borrows the EIP's number, drop the "within EIP-8252
tolerance" overclaim, note that full-window retention under healthy finality would
also need retention across finalized persists (which the EIP does not require), and
fix the Patricia pruning-boundary wording from "a fixed 64 blocks" to the
configurable Pruning.PruningBoundary.

Add Eip8252_ForcedPersist_KeepsWholeWindowReconstructable and
Eip8252_ForcedPersist_KeepsPersistedTierWindowStateReconstructable, which drive the
forced persist at production defaults and assert the in-window state (in each tier)
is retained and the base lands on the floor without a CompactSize gap.
Revert the force-persist window-floor guard added in 1bf38bf: it deferred
persistence aggressively enough that a cold engine-API reorg (newPayload +
forkchoiceUpdated to an in-window sibling) returned SYNCING instead of
reconstructing the fork-point state. EIP-8252 retention is finality-aware --
pruning toward the finalized block already complies, and REORG_RETENTION_WINDOW
is only the inactivity-leak upper bound on how far non-finality can reach, not
an always-on head-denominated retention target. Nethermind's native FlatDb
fold-toward-finalized behaviour already matches this, so the guard was
unnecessary. This restores PersistenceManager/SnapshotRepository to their
pre-1bf38bf behaviour and drops the two supporting tests.

Keep the legitimate doc fixes: describe LongFinalityMaxReorgDepth as the
finality-stall backstop that borrows the EIP's number, and correct the Patricia
pruning-boundary wording to the configurable Pruning.PruningBoundary (default
64, floored at 64, raised by many shipped configs). Soften the integration-test
comment that overstated retention as the whole non-finality span.
public ulong CompressedNodeRecordBufferMemoryBudget { get; set; } = 500UL.MiB;
public bool EnableLongFinality { get; set; } = true;
public ulong LongFinalityMaxReorgDepth { get; set; } = 90000;
public ulong LongFinalityMaxReorgDepth { get; set; } = ReorgRetentionWindow;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] The higher default lets payload validation discard the forkchoice-selected head’s state without a forkchoice change. With finality stalled at persisted base B and the selected head at B+100,000, the old backstop would already have folded past B, so NewPayloadHandler.ShouldProcessBlock could not execute a competing child of B. The new default retains B and lets that branch execute. EthereumMerge leaves the block-tree head unchanged, but FlatDbManager.AddSnapshot records each newly committed payload as the last committed state. If the competing branch reaches B+262,145 while forkchoice still selects the original head, ForcedPersistSeed follows the competing tip. FindSnapshotToPersist only checks for a conflicting finalized root at the fold endpoint, which is above B. RemoveSiblingAndDescendents then drops the selected branch’s snapshots if the branches have different state roots there, leaving the node unable to execute the next child of its selected head locally. Use the forkchoice-selected head for the depth and seed, and verify the fold endpoint lies on its ancestry before pruning. EIP-3675, Fork choice rule

/// post-state back to the block where finality was lost, up to this many blocks, without external sync.
/// Under healthy finality the client is NOT required to keep every block within head-W; state folds
/// toward the finalized boundary as usual (see PersistenceManager), and this window only bounds how
/// deep the retained span may grow while finality is stuck. Used as the default long-finality

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] The new summary and CLI help say the larger backstop only affects retention during a finality stall. With the supported setting FlatDb.CompactSize=1, NextFullCompactionAfter returns ulong.MaxValue, which disables finalized-driven RocksDB folds even while finality advances. With long finality enabled and the default zero byte budget, the strict depth check moves the first fold from 90,001 to 262,145 blocks and extends the steady-state snapshot span by 172,144 blocks on a steadily advancing chain. Document the additional disk retention in this mode.

bool EnableLongFinality { get; set; }

[ConfigItem(Description = "Force-persist backstop used when EnableLongFinality is on, in place of MaxReorgDepth. The persisted-snapshot tier serves deep reorgs, so this is much larger than the non-long-finality backstop.", DefaultValue = "90000")]
[ConfigItem(Description = "Force-persist backstop used when EnableLongFinality is on, in place of MaxReorgDepth. The persisted-snapshot tier serves deep reorgs down to this depth, so this is much larger than the non-long-finality backstop. The default is the EIP-8252 REORG_RETENTION_WINDOW (262144 blocks = 8192 epochs x 32 slots = 2^18, ~36.4 days): the inactivity-leak-bounded cap on non-finality. During a finality stall the node must be able to reconstruct post-state back to where finality was lost, up to this many blocks, without sync; under healthy finality state still folds toward the finalized boundary, so this only bounds how deep the retained span grows while finality is stuck. Operators may override it; EnableLongFinality=false drops to the smaller in-memory MaxReorgDepth backstop and opts out of EIP-8252 retention. Only the flat-state store honours this window; nodes still on the legacy patricia-trie pruning store keep the configurable Pruning.PruningBoundary (default 64, floored at a 64-block minimum and raised well above it by many shipped configs, e.g. 256 or 4096) and gain nothing from this setting.", DefaultValue = "262144")]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] The new help says the snapshot tier can reconstruct back to the start of a finality stall within this depth, but a positive MaxInMemorySnapshotBytes can advance the RocksDB base much sooner. If the budget is first exceeded at B+160 with finality stalled at an aligned persisted base B, the 160 in-memory bases do not exceed the conversion threshold. TryFindByteBudgetPersist can fold B through B+32 because 128 blocks remain above the new base. With history disabled, HasStateForBlock then rejects B. Qualify the help to say that byte pressure can shorten the window while the oldest snapshots are still in memory.

{
/// <summary>
/// EIP-8252 REORG_RETENTION_WINDOW: 262144 blocks = 8192 epochs x 32 slots = 2^18 (~36.4 days at
/// 12s slots). The inactivity-leak-bounded cap on how far non-finality can extend. EIP-8252 requires

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] The new summary and CLI help describe 8,192 epochs as an upper limit on non-finality. EIP-8252 chooses that retention horizon to cover approximately 79% initial offline stake. At 80%, its own inactivity-leak model gives about 8,353 epochs to recover finality. Describe 262,144 blocks as the chosen local retention horizon and remove the claimed cap on stall duration. EIP-8252, Choice of constant

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's aligning things with the CL and history expiry:
https://eips.ethereum.org/EIPS/eip-8383

@svlachakis svlachakis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current EIP-8252 draft permits folding toward finality. The stalled-finality case remains. If finality stops at B+16 and the first forced fold advances the base to B+32, an unfinalized fork point between them can lose its state while it is still within 262,144 blocks of the head. Please cover an unfinalized fork point in the forced-fold test and align the documented guarantee with the result. Existing thread EIP-8252

Correct the EIP-8252 docs after review: 262144 is the chosen retention
horizon (~79% offline stake), not a hard cap on non-finality; the setting
is a force-persist backstop DEPTH, not a per-block window guarantee. The
forced-persist fold advances the base in CompactSize chunks and is not
clamped to the window floor, so right after a forced persist the boundary
(including the finalized block's own post-state) can be pruned -- a known
gap vs a strict window, floor-clamped selection tracked as follow-up. Also
document that CompactSize=1 and a positive MaxInMemorySnapshotBytes shift
retention, and that full-window coverage needs retaining state across
finalized persists.
@nerolation

Copy link
Copy Markdown
Contributor Author

You're right, the fold can overshoot the finalized boundary. I've fixed the docs to stop claiming otherwise, and I'm happy to add the floor-clamp (seed and depth from the forkchoice head, candidate deferred if it crosses the floor).

Per Nethermind's review: the forced-persist (deep-stall) fold advanced the
RocksDB base in CompactSize chunks without clamping to the window floor
(head - backstop), so under a stall past the window it could prune state the
EIP-8252 window still requires -- including the last finalized block's
post-state, which a reorg may fork at.

Defer a fine (<= CompactSize) forced fold whose new base would cross that
floor, like the finalized-driven path already defers a partial chunk. The base
then lags the floor by at most CompactSize until the floor reaches the chunk
boundary, bounding the memory overshoot without dropping in-window state.
Coarser units (a bulk-imported wide base, a large-compacted span) are let
through: their intermediate per-block states were never individually
reconstructable, so deferring would only pin memory. The byte-pressure path is
deliberately left unclamped -- it must relieve memory to avoid OOM. Updated the
backstop tests that asserted the old overshoot to the clamped behavior.

The seed/ancestry concern (the forced seed following a competing tip) is a
separate follow-up.

@svlachakis svlachakis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The floor check fixes the ordinary forced-fold overshoot from my previous review. Low - PersistenceManager.cs:217 reports a missing candidate after a valid candidate was deliberately deferred. Skip the warning on that path. Please also assert that the unfinalized fork point remains readable after persistence. Window test

…w readability

When the force-persist clamp defers a candidate whose fold would cross the
EIP-8252 window floor, a candidate was found and held back on purpose, so the
"neither persistence nor conversion found a candidate" stall warning is wrong.
Suppress it on that path and trace the deliberate deferral at debug instead.

Add AddToPersistence_ForcedFoldAcrossWindowFloor_KeepsInWindowForkPointReadable:
drives the persist under a stalled finality and asserts the unfinalized in-window
fork point stays reconstructable afterwards. It fails without the clamp (the base
advances past the floor and the oldest in-window blocks are pruned).
@nerolation
nerolation force-pushed the eip8252-reorg-retention branch from 2ecfc4c to 70ceed4 Compare November 29, 2026 12:39

@svlachakis svlachakis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The deferral no longer emits the missing-candidate warning. Low - PersistenceManagerTests.cs:870: HasState checks snapshot presence. Open the floor block through the normal reader and check a known value to prove the state can still be reconstructed.

…napshot is present

The readability test asserted HasState, which only checks that a snapshot object
exists. Open the floor block through the normal read path instead — assemble its
state and read a known account value through a ReadOnlySnapshotBundle, the same
gather FlatStateReader reads through — so the test proves the state actually
rebuilds. Still fails without the clamp (the floor block is pruned).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants